<template>
  <div class="app-container">
    <el-form class="formList"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px">
      <el-row>

        <el-form-item label="客户姓名"
          prop="customerName">
          <el-input v-model="queryParams.customerName"
            placeholder="请输入客户姓名"
            clearable
            size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="客户手机号"
          prop="phone">
          <el-input v-model="queryParams.phone"
            placeholder="请输入客户手机号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item style="margin-left: 22px">
          <el-button type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh"
            size="mini"
            @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>

    </el-form>

    <el-row class="row-mbinfo">

      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleSave">新增</el-button>
      </el-col>

      <el-col :span="1.5" style="margin-left: 10px">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除
        </el-button>
      </el-col> -->

      <right-toolbar :showSearch.sync="showSearch"
        @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="divTable">
      <el-table border
        v-loading="loading"
        :data="brandList"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection"
          width="55"
          align="center" />
        <el-table-column label="客户头像"
          align="center"
          prop="subscribeDate">
          <template slot-scope="scope">
            <el-image style="width:60px;height:60px"
              v-if="scope.row.headImage != null && scope.row.headImage != '' "
              slot="reference"
              :src="scope.row.headImage"
              class="image-rows"
              :preview-src-list="[scope.row.headImage]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="客户姓名"
          align="center"
          prop="customerName">

        </el-table-column>

        <el-table-column label="客户性别"
          align="center"
          prop="customerSex">
          <template slot-scope="scope">
            <span>{{ scope.row.customerSex =='1' ? '男':'女'}}</span>
          </template>
        </el-table-column>

        <el-table-column label="出生日期"
          align="center"
          prop="birthday">

        </el-table-column>

        <el-table-column label="年龄"
          align="center"
          prop="age">

        </el-table-column>

        <el-table-column label="手机号"
          align="center"
          prop="phone">
          <template slot-scope="scope">
            <span>{{ scope.row.phone }}</span>
          </template>
        </el-table-column>

        <el-table-column label="会员等级"
          align="center"
          prop="levelName">
          <template slot-scope="scope">
            <span>{{ scope.row.levelName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址"
          align="center"
          min-width="150"
          show-overflow-tooltip
          prop="subscribeDate">
          <template slot-scope="scope">
            <span>{{ scope.row.province }}{{ scope.row.city }}{{ scope.row.area }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作"
          align="center"
          prop="createTime"
          width="200">
          <template slot-scope="scope">
            <el-button type="text"
              size="mini"
              icon="el-icon-zoom-in"
              @click="handlee(scope.row)">面诊信息</el-button>
            <el-button type="text"
              size="mini"
              icon="el-icon-zoom-in"
              v-if="scope.row.storeId"
              @click="handleDetail(scope.row)">制定方案</el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

  </div>
</template>

<script>

import {
  listSelect
} from "@/api/platform/store"
import {
  listSheet
} from "@/api/customerService/sheet";

import { onInput } from "@/utils/util";
export default {
  name: "Brand",
  components: {

  },
  data () {
    return {

      selectedDataCopy: [{}],
      selectedData: [],
      storeOpen: false,
      selectedDataStore: {},
      couponOpen: false,
      selectedDataCoupon: {},
      cardAOpen: false,
      selectedDataCard: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中数组的名字
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 储值/系列表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openA: false,
      // 用于类别关联的分类显示
      dialogVisible: false,
      //常用状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        phone: null,
        startTime: null,
        endTime: null,
        applyAuthTimeArray: [],
        nickName: null,
        storeId: null,
      },
      // 商品
      productOpen: false,
      selectedDataProduct: {},



      options: [
        {
          value: "1",
          label: "已领取",
        },
        {
          value: "0",
          label: "未领取",
        },
      ],
      // 表单参数
      form: {
        customerName: null,
        phone: "",
        dataPriority: "",
        isDataValue: "",
        rightType: "",
      },
      storeInFoOptions: [],
      // 表单校验
      rules: {
        rechargeName: [
          {
            required: true,
            message: "储值名称不能为空",
            trigger: "blur",
          },
        ],
        isDataValue: [
          {
            required: true,
            message: "储值属性不能为空",
            trigger: "change",
          },
        ],
        rightType: [
          {
            required: true,
            message: "储值权益不能为空",
            trigger: "change",
          },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  created () {
    this.getList();
    // this.getDicts("sys_data_status").then((response) => {
    //   this.statusOptions = response.data;
    // });
    // listSelect().then(response => {
    //   this.storeInFoOptions = response.data || [];
    // });

  },
  watch: {
    selectedDataCopy: {
      deep: true,
      handler (newVal, oldVal) {
        let obj = newVal[0];
        if (Object.keys(obj).length > 0) {
          let arr = Object.keys(obj),
            isValue = false;
          arr.forEach((item) => {
            if (obj[item]) {
              isValue = true;
            }
          });
          if (isValue) {
            this.form.isDataValue = "1";
          } else {
            this.form.isDataValue = "";
          }
        } else {
          this.form.isDataValue = "";
        }
      },
    },
  },
  methods: {
    onInput,
    parseJsonObject (obj) {
      let jsonObJ = JSON.parse(obj);
      console.log(jsonObJ)
      return jsonObJ;
    },
    handlee (row) {
      let id = row.sheetId || 0;
      // this.$router.push("/newCustomer/data/" + id);

      this.$router.push({
        path: "/newCustomer/data/" + id, query: {
          customer: row.customerId,
        }
      });
    },
    handleDetail (row) {

      this.$router.push({
        path: "/store/customerList/newCustomer", query: {
          phone: row.phone,
          storeId: row.storeId
        }
      });
    },
    tabResponCard () {
      this.selectedDataCard = {};
    },
    tabResponCoupon () {
      this.selectedDataCoupon = {};
    },
    tabRespon () {
      this.selectedDataStore = {};
    },
    tabResponProduct () {
      this.selectedDataProduct = {};
    },
    dataPriorityInput (value) {
      let js = value + "";
      return js.replace(/^(0+)|[^\d]+/g, "");
    },
    /** 查询储值/系列列表 */
    getList () {
      if (this.queryParams.applyAuthTimeArray != null && this.queryParams.applyAuthTimeArray.length > 0) {
        let arr = this.queryParams.applyAuthTimeArray;
        this.queryParams.startTime = arr[0] + " 00:00:00";
        this.queryParams.endTime = arr[1] + " 23:59:59";
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
      this.loading = true;
      listSheet(this.queryParams).then((response) => {
        this.brandList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    p (s) {
      return s < 10 ? "0" + s : s;
    },

    selectCommodityCoupon () {
      this.$forceUpdate();
      this.couponOpen = true;
      console.log(this.couponOpen);
      // this.$nextTick(() => {
      //   this.$refs["selTableCoupon"].greet(this.selectedDataCoupon);
      // });
    },

    //调用子组件中方法，向子组件传值
    selectCommodity () {
      this.$forceUpdate();
      this.openA = true;
      this.$nextTick(() => {
        this.$refs["selTable"].greet(this.selectedData);
      });
    },

    selectCommodityCard () {
      this.$forceUpdate();
      this.cardAOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableCard"].greet(this.selectedDataCard);
      });
    },

    selectCommodityProduct () {
      this.productOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableProduct"].greet(this.selectedDataProduct);
      });
    },

    multipleSelection (data) {
      this.openA = false;
      this.selectedData = data;
      // this.$nextTick(() => {
      //   this.$refs.child.getList();
      // });
    },

    selectCommodityService () {
      this.$forceUpdate();
      this.storeOpen = true;
      // this.$nextTick(() => {
      //   this.$refs["selTable"].greet(this.selectedDataStore);
      // });
    },

    toCloseBoxCoupon () {
      this.couponOpen = false;
    },

    toCloseBoxCard () {
      this.cardAOpen = false;
    },

    toCloseBoxProduct () {
      this.productOpen = false;
    },

    toCloseBoxStore () {
      this.storeOpen = false;
    },

    toCloseBox () {
      this.open = false;
    },

    multipleSelectionCoupon (data) {
      this.couponOpen = false;
      this.selectedDataCoupon = data;
      this.$nextTick(() => {
        this.$refs.childCoupon.getList();
      });
    },

    multipleSelectionStore (data) {
      this.storeOpen = false;
      this.selectedDataStore = data;
      this.$nextTick(() => {
        this.$refs.childStore.getList();
      });
    },

    multipleSelectionCard (data) {
      this.cardAOpen = false;
      this.selectedDataCard = data;
      this.$nextTick(() => {
        this.$refs.childCard.getList();
      });
    },

    multipleSelectionProduct (data) {
      this.productOpen = false;
      this.selectedDataProduct = data;
      this.$nextTick(() => {
        this.$refs.childProduct.getList();
      });
    },

    getSTime (val) {
      //手动赋值，使其通过校验

      const d = new Date(val[0]);
      const resDate =
        d.getFullYear() +
        "-" +
        this.p(d.getMonth() + 1) +
        "-" +
        this.p(d.getDate());
      const resTime =
        this.p(d.getHours()) +
        ":" +
        this.p(d.getMinutes()) +
        ":" +
        this.p(d.getSeconds());
      this.form.startTime = resDate + " " + resTime;
      const c = new Date(val[1]);
      const resDatec =
        c.getFullYear() +
        "-" +
        this.p(c.getMonth() + 1) +
        "-" +
        this.p(c.getDate());
      const resTimec =
        this.p(c.getHours()) +
        ":" +
        this.p(c.getMinutes()) +
        ":" +
        this.p(c.getSeconds());
      this.form.endTime = resDatec + " " + resTimec;
    },

    handleChange (value) {
      console.log(value);
    },

    handleRemove (file, fileList) { },
    handlePictureCardPreviewLogo (file) {
      this.logoUr = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreviewImg (file) {
      this.deviceImage = file.url;
      this.dialogVisible = true;
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 关联的取消按钮
    cancelBrand () {
      this.openBrand = false;
      this.reset();
    },
    // 表单重置
    reset () {
      // this.form = {
      //   rechargeName: null,
      //   rechargeIcon: null,
      //   isDataValue: '',
      //   dataPriority: 10,
      //   rightType: ''
      // };
      this.form.rechargeName = null;
      this.form.rechargeIcon = null;
      this.form.isDataValue = "";
      this.form.dataPriority = 10;
      this.form.rightType = "";
      this.resetForm("form");
      if (this.$refs["form"]) {
        this.$refs["form"].resetFields();
      }
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 储值菜单 */
    getMenuTreeselect () {
      menuTreeselect().then((response) => {
        this.menuOptions = response.data;
      });
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.rechargeId);
      this.names = selection.map((item) => item.rechargeName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      //用于禁用删除
      if (this.multiple == false) {
        for (var i = 0; i < selection.length; i++) {
          var element = selection[i];
          if ("1" === element.dataStatus) {
            this.multiple = true;
            break;
          }
        }
      }
    },
    // 状态修改
    handleStatusChange (row) {
      let text = row.dataStatus === "0" ? "无效" : "有效";
      this.$confirm(
        '确定要把储值名称为"' + row.rechargeName + '"设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateBrandStatus(row.rechargeId, row.dataStatus);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        })
        .catch(function () {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
    },

    // 状态修改
    handleStatusChangeA (row) {
      let text = row.isRecommend === "0" ? "不推荐" : "推荐";
      this.$confirm(
        '确定要把储值名称为"' + row.rechargeName + '"设为' + text + "吗？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateBrandStatusA(row.rechargeId, row.isRecommend);
        })
        .then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        })
        .catch(function () {
          row.isRecommend = row.isRecommend === "0" ? "1" : "0";
        });
    },

    /** 新增按钮操作 */
    handleAdd () {
      this.selectedDataCopy = [{}];
      this.reset();
      this.open = true;
      this.title = "添加储值";
    },
    handleSave () {
      this.$router.push("/service/recharge/data/");

    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.$router.push("/service/recharge/editData/" + row.rechargeId);

      // this.reset();
      // const rechargeId = row.rechargeId || this.ids;
      // getBrand(rechargeId).then((response) => {
      //   this.form = response.data;
      //   console.log(this.form);
      //   this.selectedDataCopy[0].rechargeMoney = this.form.rechargeMoney;
      //   this.selectedDataCopy[0].goldCoin = this.form.goldCoin;
      //   this.selectedDataCopy[0].silverCoin = this.form.silverCoin;
      //   this.selectedDataCopy[0].score = this.form.score;
      //   this.form.timeValue = [];
      //   this.form.timeValue.push(this.form.startTime || "");
      //   this.form.timeValue.push(this.form.endTime || "");
      //   this.open = true;
      //   this.title = "修改储值";
      // });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs.childs.selectImgs();
      this.form.rechargeMoney = this.selectedDataCopy[0].rechargeMoney;
      this.form.goldCoin = this.selectedDataCopy[0].goldCoin;
      this.form.silverCoin = this.selectedDataCopy[0].silverCoin;
      this.form.score = this.selectedDataCopy[0].score;

      // 选择权益
      if (this.form.rightType == "coupon") {
        // 获取id this.selectedDataCoupon
        this.form.rightObjectId = this.selectedDataCoupon.couponUid;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择优惠券数据");
          return;
        }
      } else if (this.form.rightType == "card") {
        // 获取id  this.selectedDataCard
        this.form.rightObjectId = this.selectedDataCard.cardId;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择套餐卡数据");
          return;
        }
      } else if (this.form.rightType == "service") {
        // 获取id  this.selectedDataStore
        this.form.rightObjectId = this.selectedDataStore.itemId;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择服务项目数据");
          return;
        }
      } else if (this.form.rightType == "product") {
        // 获取id  this.selectedDataProduct
        this.form.rightObjectId = this.selectedDataProduct.productUid;
        if (this.form.rightObjectId == null) {
          this.msgError("请选择商品数据");
          return;
        }
      }

      console.log(this.form);
      return
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.rechargeId != null) {
            updateBrand(this.form).then((response) => {
              // updateRight(this.form)
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.selectedDataCard = {};
              this.selectedDataCoupon = {};
              this.selectedDataStore = {};
              this.selectedDataProduct = {};
            });
          } else {
            addBrand(this.form).then((response) => {
              // form.rightObjectId=
              // addRight(this.form)
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.selectedDataCard = {};
              this.selectedDataCoupon = {};
              this.selectedDataStore = {};
              this.selectedDataProduct = {};
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const deviceIds = row.rechargeId || this.ids;
      const names = row.rechargeName || this.names;
      this.$confirm('是否确认删除储值名称为"' + names + '"的储值?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delBrand(deviceIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "device/brand/export",
        {
          ...this.queryParams,
        },
        `商品储值.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.treeOne {
  display: inline-block;
  margin-right: 200px;
}

.treeTwo {
  display: inline-block;
}

.image-rows {
  width: 80px;
  height: auto;
}
</style>
